package org.easy.core.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


public class AesUtil {

    //可配置到Constant中，并读取配置文件注入,16位,自己定义
    private static final String DEFAULT_KEY = "12v4g79di7lp64gh";

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";


    public static String encrypt(String content, String encryptKey) {
        try {
            SecretKeySpec aes = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), "AES");

            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.ENCRYPT_MODE, aes);
            byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.encode(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encryptStr, String decryptKey) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), "AES"));
            byte[] decryptBytes = cipher.doFinal(Base64.decode(encryptStr));
            return new String(decryptBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String encrypt(String content) {
        return encrypt(content, DEFAULT_KEY);
    }

    public static String decrypt(String encryptStr) {
        return decrypt(encryptStr, DEFAULT_KEY);
    }


    public static void main(String[] args) {


        System.out.println(AesUtil.encrypt("{\"cleaner\": true,\"cncMark\": \"992c725fe9a746a3b4899c5c22ef1111\",\"hardwareCode\": \"53dc15\",\"pressure\": \"false\",\"runningStatus\": true,\"saveDoor\": true,\"binDoor\":true}"));
        System.out.println(AesUtil.decrypt("xeikwWyfZsPTCQ/Ax0Rg9zRQVyxYgxnf9xVL6cIxO18kp/pKUEqLct87NAdC8+hY"));
    }

}
